<template>
  <div class="lm-form-container">
    <div class="lm-form-item">
      <span class="required-star" v-if="isRequired">*</span>
      <label :style="labelStyle" class="lm-form-item_label">{{ label }}</label>
      <div class="lm-form-item_content">
        <slot></slot>
        <div v-if="error" class="error-tips">{{ error }}</div>
      </div>
    </div>
  </div>
</template>

<script>
import AsyncValidator from "async-validator";
export default {
  name: "LmFormItem",
  inject: {
    Form: {},
  },
  props: {
    label: {
      type: String,
      default: "",
    },
    prop: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      error: "",
    };
  },
  computed: {
    labelStyle() {
      return {
        width: this.Form.labelWidth,
      };
    },
    isRequired() {
      return (
        this.prop &&
        (this.Form.rules[this.prop] || []).some((con) => con.required)
      );
    },
  },
  mounted() {
    this.$on("validate", this.startValidate);
  },
  methods: {
    // 校验
    startValidate() {
      const { model, rules } = this.Form;
      let descriptor = {
        [`${this.prop}`]: rules[this.prop],
      };

      let validator = new AsyncValidator(descriptor);

      return validator.validate(
        {
          [`${this.prop}`]: model[this.prop],
        },
        (error, fileds) => {
          if (error) {
            this.error = error[0].message;
          } else {
            this.error = ``;
          }
        }
      );
    },
  },
};
</script>

<style lang="scss" scoped>
.lm-form-item {
  margin-bottom: 25px;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  .lm-form-item_label {
    text-align: right;
    vertical-align: middle;
    float: left;
    font-size: 14px;
    color: #606266;
    line-height: 40px;
    padding: 0 12px 0 0;
    box-sizing: border-box;
  }
  .lm-form-item_content {
    line-height: 40px;
    position: relative;
    font-size: 14px;
    overflow: hidde;
  }
}
.lm-form-container {
  position: relative;
  margin-bottom: 20px;

  &.is-error {
    /* margin-bottom: 5px; */
  }
}

.lm-form-item {
  display: flex;
  align-items: center;
}

.lm-form-item--label {
  text-align: right;
  vertical-align: middle;
  float: left;
  font-size: 14px;
  color: #606266;
  line-height: 40px;
  padding: 0 12px 0 0;
  box-sizing: border-box;
}

.required-star {
  color: red;
}

.error-tips {
  color: #f56c6c;
  font-size: 14px;
  line-height: 1;
  padding-top: 2px;
  position: absolute;
  top: 100%;
  left: 0;
}

.error-fade-enter,
.error-fade-leave-to {
  transform: translateY(-10px);
  opacity: 0;
}

.error-fade-enter-active,
.error-fade-leave-active {
  transition: all 0.5s;
}
</style>